package controller

import (
	"config"
	"model"
	"net/http"
	"spirit/mongodb"
	"spirit/utils"
	D "spirit/utils/date"
	"time"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

//普通用户查询体检结果信息
type OrdinaryUserController struct{}

func sessionApp() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		account := session.Get("ordinaryPhone")
		role := session.Get("ordinaryIdCard")
		if account == nil || role == nil {
			c.Abort()
			c.HTML(http.StatusOK, "mobile/ordinary/login.html", gin.H{"code": -1, "msg": "登录超时请重新登录"})
			return
		}
	}
}
func (ctrl *OrdinaryUserController) Router(router *gin.Engine) {
	OrdinaryUserGroup := router.Group("/mobile/ordinary/")
	OrdinaryUserGroup.GET("/login", ordinaryUserLogin)
	OrdinaryUserGroup.POST("/validate", ordinaryUserValidate)
	OrdinaryUserGroup.GET("/info", ordinaryUserInfo)
	OrdinaryUserGroup.GET("/downLoad", downLoad)
	OrdinaryUserGroup.Use(sessionApp())
	{
		//菜单
		OrdinaryUserGroup.GET("/examination", examinationResult)
		OrdinaryUserGroup.GET("/guidingOpinions", guidingOpinions)
		OrdinaryUserGroup.GET("/inspectionRecord", inspectionRecord)
		OrdinaryUserGroup.GET("/feedback", feedback)
		//检查结果
		OrdinaryUserGroup.GET("/baseInfo", baseInfo)
		OrdinaryUserGroup.GET("/lifeStyle", lifeStyle)
		OrdinaryUserGroup.GET("/familyHistory", familyHistory)
		OrdinaryUserGroup.GET("/pastMedicalHistory", pastMedicalHistory)
		OrdinaryUserGroup.GET("/physicalExamination", physicalExamination)
		OrdinaryUserGroup.GET("/electrocardiogram", electrocardiogram)
		OrdinaryUserGroup.GET("/laboratoryExamination", laboratoryExamination)
		OrdinaryUserGroup.GET("/riskRating", riskRating)
		OrdinaryUserGroup.GET("/cervicalVessels", cervicalVessels)
		//获取用户信息
		OrdinaryUserGroup.POST("/getUserData", getUserData)
		//用户提交反馈意见
		OrdinaryUserGroup.POST("/saveFeedback", saveFeedback)
		//医生回复
		OrdinaryUserGroup.POST("/replyFeedback", replyFeedback)
		//获取指导意见
		OrdinaryUserGroup.POST("/getFeedback", getFeedback)
		//退出
		OrdinaryUserGroup.GET("/signOut", signOut)
	}
}

//
func downLoad(ctx *gin.Context) {
	//跳转移动端 APP下载页面
	ctx.HTML(http.StatusOK, "mobile/ordinary/index.html", nil)
}

//
func signOut(ctx *gin.Context) {
	session := sessions.Default(ctx)
	session.Clear()
	session.Save()
	ctx.HTML(http.StatusOK, "mobile/ordinary/login.html", nil)
}

//
func getFeedback(ctx *gin.Context) {
	result := &model.BaseResult{}
	phone := GetSessionInfo("ordinaryPhone", ctx)
	idCard := GetSessionInfo("ordinaryIdCard", ctx)
	userName := GetSessionInfo("ordinaryUserName", ctx)
	if phone != "" && idCard != "" && userName != nil {
		query := make(map[string]interface{}, 0)
		query["phone"] = phone
		query["idCard"] = idCard
		query["userName"] = userName
		query["status"] = 1
		tbName := "feedback"
		m := mongodb.Find(tbName, query, `{"createTime":1}`, nil, false, -1, -1)
		if len(*m) > 0 {
			result.Code = 0
			for _, val := range *m {
				replyTime := val["replyTime"]
				val["replyTime"] = D.FormatDateWithObj(&replyTime, D.Date_Short_Layout)
			}
		} else {
			result.Code = 1
		}
		result.Data = m
	} else {
		result.Code = 1
		result.Data = nil
	}
	ctx.JSON(http.StatusOK, result)
}

//
func replyFeedback(ctx *gin.Context) {
	result := &model.BaseResult{}
	_id := ctx.Request.FormValue("_id")
	replyContent := ctx.Request.FormValue("replyContent")     //指导内容
	guidePhysician := ctx.Request.FormValue("guidePhysician") //指导医师
	replyTime := time.Now().Unix()
	if _id != "" && replyContent != "" {
		query := make(map[string]interface{}, 0)
		query["replyContent"] = replyContent
		query["guidePhysician"] = guidePhysician
		query["replyTime"] = replyTime
		query["status"] = 1 //暂未回复0 已经回复1
		tbName := "feedback"
		b := mongodb.UpdateById(tbName, _id, query)
		if b {
			result.Code = 0
			result.Msg = "提交成功"
		} else {
			result.Code = 1
			result.Msg = "提交失败"
		}
	} else {
		result.Code = 1
		result.Msg = "提交失败"
	}
	ctx.JSON(http.StatusOK, result)
}

//
func saveFeedback(ctx *gin.Context) {
	result := &model.BaseResult{}
	phone := GetSessionInfo("ordinaryPhone", ctx)
	idCard := GetSessionInfo("ordinaryIdCard", ctx)
	userName := GetSessionInfo("ordinaryUserName", ctx)
	textarea := ctx.Request.FormValue("textarea")
	createTime := time.Now().Unix()
	if phone != "" && idCard != "" && userName != nil && textarea != "" {
		query := make(map[string]interface{}, 0)
		query["phone"] = phone
		query["idCard"] = idCard
		query["userName"] = userName
		query["textarea"] = textarea
		query["createTime"] = createTime
		query["feedTime"] = createTime
		query["status"] = 0  //暂未回复0 已经回复1
		query["style"] = "F" //反馈
		tbName := "feedback"
		id := mongodb.Save(tbName, query)
		if id != "" {
			result.Code = 0
			result.Msg = "提交成功"
		} else {
			result.Code = 1
			result.Msg = "提交失败"
		}
	} else {
		result.Code = 1
		result.Msg = "提交失败"
	}
	ctx.JSON(http.StatusOK, result)
}

//
func getUserData(ctx *gin.Context) {
	result := &model.BaseResult{}
	phone := GetSessionInfo("ordinaryPhone", ctx)
	idCard := GetSessionInfo("ordinaryIdCard", ctx)
	listSY := ctx.Request.FormValue("listSY")
	//log.Println(phone, "++++", idCard)
	res := make([]*map[string]interface{}, 0)
	if phone != "" && idCard != "" {
		tbName := config.TbBaseName
		query := make(map[string]interface{}, 0)
		query["baseInfo.phone"] = phone
		query["baseInfo.idCard"] = idCard
		if listSY != "" {
			//查往年历史
			if len(config.ScreenYearRecord) > 0 {
				for _, year := range config.ScreenYearRecord {
					tbName = "infoCollection_" + year
					userData := mongodb.FindOne(tbName, query)
					if *userData != nil {
						res = append(res, userData)
					}
				}
			}
		} else {
			//screenYear:=ctx.Request.FormValue("screenYear")
			//查最新的一年检查记录
			userData := mongodb.FindOne(tbName, query)
			if *userData != nil {
				res = append(res, userData)
			}else{
				//查历史,获取最新一年数据
				for _, year := range config.ScreenYearRecord {
					tbName = "infoCollection_" + year
					userData := mongodb.FindOne(tbName, query)
					if *userData != nil {
						res = append(res, userData)
						break
					}
				}
			}
		}
		//res := mongodb.Find(tbName, query, `{"createTime":1}`, nil, false, -1, -1)
		if res != nil && len(res) > 0 {
			for _, val := range res {
				baseInfoD := utils.ObjToMap((*val)["baseInfo"])
				area, _ := (*baseInfoD)["area"].(string)
				(*baseInfoD)["area"] = getAreaNameByCode(area)
				screenOrganCode, _ := (*baseInfoD)["screenOrganCode"].(string)
				(*baseInfoD)["screenOrganCode"] = getAreaNameByCode(screenOrganCode)
				createTime := (*val)["createTime"]
				(*val)["createTime"] = D.FormatDateWithObj(&createTime, D.Date_Short_Layout)
			}

			if listSY == "A" {
				result.Data = res
			} else {
				_res := res[0]
				result.Data = _res
			}
		} else {
			result.Msg = "无筛查记录信息"
			result.Data = nil
		}
		result.Code = 1

	} else {
		result.Code = -1
		result.Msg = "无筛查记录信息"
	}
	ctx.JSON(http.StatusOK, result)
}

//基本信息
func baseInfo(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/baseInfo.html", nil)
}

//生活方式
func lifeStyle(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/lifeStyle.html", nil)
}

//家族史
func familyHistory(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/familyH.html", nil)
}

//既往病史
func pastMedicalHistory(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/pastMH.html", nil)
}

//体格检查
func physicalExamination(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/physicalE.html", nil)
}

//心电图
func electrocardiogram(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/ecg.html", nil)
}

//实验室检查
func laboratoryExamination(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/laboratoryE.html", nil)
}

//心脑血管风险评级
func riskRating(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/riskRating.html", nil)
}

//颈部血管超声
func cervicalVessels(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/cervicalV.html", nil)
}

//登录后跳转检查结果页面
func examinationResult(ctx *gin.Context) {
	//year := ctx.Request.FormValue("year")
	ctx.HTML(http.StatusOK, "mobile/ordinary/exaResult.html", nil)
}

//指导意见页面
func guidingOpinions(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/guiding.html", nil)
}

//检查记录页面
func inspectionRecord(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/inspection.html", nil)
}

//意见反馈页面
func feedback(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/feedback.html", nil)
}

//跳转登录页面
func ordinaryUserLogin(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "mobile/ordinary/login.html", nil)
}

//登录验证
func ordinaryUserValidate(ctx *gin.Context) {
	result := &model.BaseResult{}
	phone := ctx.Request.FormValue("phone")
	idCard := ctx.Request.FormValue("idCard")
	//log.Println(phone, "---", idCard)
	screenYear := ""
	if phone != "" && idCard != "" {
		query := make(map[string]interface{}, 0)
		query["baseInfo.phone"] = phone
		query["baseInfo.idCard"] = idCard

		queryTbNames := make([]string, 0)
		queryTbNames = append(queryTbNames, config.CurrentYear)

		for _, year := range config.ScreenYearRecord {
			queryTbNames = append(queryTbNames, year)
		}
		b := false
		for _, year := range queryTbNames {
			tb := "infoCollection_" + year
			res := mongodb.FindOne(tb, query)
			if *res != nil && len(*res) > 0 {
				session := sessions.Default(ctx)
				session.Set("ordinaryPhone", phone)
				session.Set("ordinaryIdCard", idCard)
				baseInfoData := utils.ObjToMap((*res)["baseInfo"])
				session.Set("ordinaryUserName", (*baseInfoData)["userName"])
				session.Save()
				result.Code = 1
				result.Msg = "登录成功！"

				b = true
				screenYear = year
				result.Data = gin.H{"screenYear": screenYear}
				break
			}
		}
		if !b {
			result.Code = -1
			result.Msg = "登录未成功,请检查身份证号或手机号是否正确填写！"
		}
	} else {
		result.Code = 0
		result.Msg = "登录未成功,请检查身份证号或手机号是否正确填写！"
	}
	ctx.JSON(http.StatusOK, result)
}

//用户详情页面
func ordinaryUserInfo(ctx *gin.Context) {
	result := &model.BaseResult{}
	phone := GetSessionInfo("ordinaryPhone", ctx)
	idCard := GetSessionInfo("ordinaryIdCard", ctx)
	//log.Println(phone, "++++", idCard)
	if phone != "" && idCard != "" {
		tbName := config.TbBaseName
		query := make(map[string]interface{}, 0)
		query["baseInfo.phone"] = phone
		query["baseInfo.idCard"] = idCard
		res := mongodb.FindOne(tbName, query)
		if *res != nil && len(*res) > 0 {
			result.Code = 1
			result.Data = *res
			ctx.HTML(http.StatusOK, "mobile/ordinary/main.html", gin.H{"result": result.Data})
		} else {
			result.Code = -1
			result.Msg = "请重新登录！"
			ctx.HTML(http.StatusOK, "mobile/ordinary/login.html", gin.H{"result": result})
		}
	} else {
		result.Code = 0
		result.Msg = "请重新登录！"
		ctx.HTML(http.StatusOK, "mobile/ordinary/login.html", gin.H{"result": result})
	}
}
